package com.itguigu.wechat.controller;

import cn.hutool.jwt.JWTHeader;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itguigu.auth.service.SysUserService;
import com.itguigu.common.jwt.JwtUtils;
import com.itguigu.common.result.Result;
import com.itguigu.model.system.SysUser;
import com.itguigu.vo.wechat.BindPhoneVo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
@Controller
@Slf4j
@RequestMapping("/admin/wechat")
@CrossOrigin
public class WechatController {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private WxMpService wxMpService;

    @Value("${wechat.userInfoUrl}")
    private String userInfoUrl;

    /**
     * 微信 认证授权
     * @param returnUrl
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     */
    @GetMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl, HttpServletRequest request) throws UnsupportedEncodingException {
        /**
         * 构造oauth2授权的url连接.
         * redirectUri – 用户授权完成后的重定向链接，无需urlencode, 方法内会进行encode scope
         * scope,静默:snsapi_base, 带信息授权:snsapi_userinfo
         * state
         */
        String redirectUrl = wxMpService.getOAuth2Service().buildAuthorizationUrl(
                userInfoUrl,
                WxConsts.OAuth2Scope.SNSAPI_USERINFO,
                URLEncoder.encode(returnUrl.replace("guiguoa", "#") , "utf-8"));
        log.info("【微信网页授权】获取code,redirectURL={}", redirectUrl);
        return "redirect:" + redirectUrl;
    }

    /**
     * 获取用户信息
     * @param code
     * @param returnUrl
     * @return
     * @throws Exception
     */
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code,
                           @RequestParam("state") String returnUrl) throws Exception {
        log.info("【微信网页授权】code={}", code);
        log.info("【微信网页授权】state={}", returnUrl);
        // 获取 accessToken
        WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
        // 使用accessToken 获取 openId
        String openId = accessToken.getOpenId();
        log.info("openId: {}" , openId);
        // 获取微信用户信息
        WxOAuth2UserInfo wxMpUserInfo = wxMpService.getOAuth2Service().getUserInfo(accessToken, null);
        log.info("微信的用户信息: {}" , JSON.toJSONString(wxMpUserInfo));

        // 根据 openId 查询用户表
        SysUser sysUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getOpenId, openId));
        // 判断 是否存在
        String token = "";
        if (sysUser != null) {
            // 存在
            // 使用jwt根据用户id 和 用户名称 生成token字符串
            Map<String , Object> claims = new HashMap<>();
            claims.put("userId", sysUser.getId());
            claims.put("username", sysUser.getUsername());
            token = JwtUtils.generateJwt(claims);
        }
        if(returnUrl.indexOf("?") == -1) {
            return "redirect:" + returnUrl + "?token=" + token + "&openId=" + openId;
        } else {
            return "redirect:" + returnUrl + "&token=" + token + "&openId=" + openId;
        }
    }

    /**
     * 手机号绑定功能
     * @param bindPhoneVo
     * @return
     */
    @ApiOperation(value = "微信账号绑定手机")
    @PostMapping("bindPhone")
    @ResponseBody
    public Result bindPhone(@RequestBody BindPhoneVo bindPhoneVo) {
        // 根据手机号查询数据库
        SysUser sysUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getPhone, bindPhoneVo.getPhone()));
        // 如果存在 , 更新记录 openid
        if (sysUser != null) {
            sysUser.setOpenId(bindPhoneVo.getOpenId());
            sysUserService.updateById(sysUser);
            // 使用jwt根据用户id 和 用户名称 生成token字符串
            Map<String , Object> claims = new HashMap<>();
            claims.put("userId", sysUser.getId());
            claims.put("username", sysUser.getUsername());
            String token = JwtUtils.generateJwt(claims);
            return Result.success(token);
        } else {
            return Result.error("手机号不存在 , 请联系管理员");
        }
    }

}
